//JS 
layui.use(['element', 'layer', 'util'], function () {
    var element = layui.element;
    var layer = layui.layer;
    var util = layui.util;
    var $ = layui.$;

    //头部事件
    util.event('lay-header-event', {
        menuLeft: function (othis) { // 左侧菜单事件
            layer.msg('展开左侧菜单的操作', { icon: 0 });
        },
        menuRight: function () {  // 右侧菜单事件
            layer.open({
                type: 1,
                title: '更多',
                content: '<div style="padding: 15px;">处理右侧面板的操作</div>',
                area: ['260px', '100%'],
                offset: 'rt', // 右上角
                anim: 'slideLeft', // 从右侧抽屉滑出
                shadeClose: true,
                scrollbar: false
            });
        }
    });
});


// 首页
function shou() {
    $('.zhu').css('display', 'block')
    $('.xingxi').css('display', 'none')
    $('.geren').css('display', 'none')
    $('.jia').css('display', 'none')
    $('.bji').css('display', 'none')
    $('.tubiao').css('display', 'none')
    $('#pagination').css('display', 'block')
}

// 仪表盘
function tu() {
    $('.zhu').css('display', 'none')
    $('.tubiao').css('display', 'block')
    $('.xingxi').css('display', 'none')
    $('.geren').css('display', 'none')
    $('.jia').css('display', 'none')
    $('.bji').css('display', 'none')
    $('#pagination').css('display', 'none')

    $.ajax({
        type: 'get',
        url: 'http://47.94.4.201/index.php/index/teacher/teacherlist',
        data: {},
        dataType: 'json',
        success: a => {
            var nan = 0
            var nv = 0
            var els = 0
            a.data.data.forEach(item => {
                if (item.sex == 0) {
                    nan++
                } else if (item.sex == 1) {
                    nv++
                } else {
                    els++
                }
            })
            var chartDom = document.getElementById('main');
            var myChart = echarts.init(chartDom);
            var option;

            option = {
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    top: '5%',
                    left: 'center'
                },
                series: [
                    {
                        name: 'Access From',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: 40,
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: [
                            { value: nan, name: '男' },
                            { value: nv, name: '女 ' },
                            { value: els, name: '其他' },
                        ]
                    }
                ]
            };

            option && myChart.setOption(option);


            var chartDom = document.getElementById('main1');
            var myChart = echarts.init(chartDom);
            var option;

            option = {
                legend: {
                    top: 'bottom'
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: { show: true },
                        dataView: { show: true, readOnly: false },
                        restore: { show: true },
                        saveAsImage: { show: true }
                    }
                },
                series: [
                    {
                        name: 'Nightingale Chart',
                        type: 'pie',
                        radius: [50, 250],
                        center: ['50%', '50%'],
                        roseType: 'area',
                        itemStyle: {
                            borderRadius: 8
                        },
                        data: [
                            { value: 40, name: a.data.data[0].name },
                            { value: 38, name: a.data.data[1].name },
                            { value: 32, name: a.data.data[2].name },
                            { value: 30, name: a.data.data[3].name },
                            { value: 28, name: a.data.data[4].name },
                            { value: 26, name: a.data.data[5].name },
                        ]
                    }
                ]
            };

            option && myChart.setOption(option);
        },
        error: e => {
            console.log(e);
        }
    })
}

// ------------------------------分页---------------------------------------
const apiUrl = "http://47.94.4.201/index.php/index/teacher/teacherlist";
let currentPage = 1;
const pageLimit = 10;

// 请求数据
async function fetchData(page) {
    if (page < 1) return;

    const response = await fetch(`${apiUrl}?page=${page}&pagelimit=${pageLimit}`);
    const result = await response.json();

    if (result.code === 0) {
        const dataList = result.data.data;
        const pageCount = result.data.pagecount;

        if (page > pageCount) return;

        currentPage = page;
        renderList(dataList);
        document.getElementById("current-page").innerText = currentPage;
        document.getElementById("total-pages").innerText = Math.ceil(pageCount / 8);
    }
}
// ---------------------讲师管理列表-----------------------
function renderList(data) {
    const dataListDiv = document.getElementById("data-list");
    data.forEach(item => {
        if (item.sex == 1) {
            item.sex = '女'
        } else if (item.sex == 0) {
            item.sex = '男'
        } else {
            item.sex = '其他'
        }
    })
    dataListDiv.innerHTML = data
        .map(item => `
            <tr>
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>${item.nick}</td>
                <td>${item.birthdata}</td>
                <td>${item.sex}</td>
                <td>${item.iphone}</td>
                <td><button type="button" lay-on="page" onclick="look(${item.id})" id='look'>查看</button> 
                <button onclick="bji(${item.id})" id='look'>编辑</button> 
                <button class="del" onclick="del(${item.id})">删除</button></td>
            </tr>`)
        .join("");
}
fetchData(1); // 初始化加载第一页


// ------------------------------添加个人中心------------------------------
function people() {
    $('.xingxi').css('display', 'block')
    $('.zhu').css('display', 'none')
    $('.geren').css('display', 'none')
    $('.jia').css('display', 'none')
    $('.bji').css('display', 'none')
    $('.tubiao').css('display', 'none')
}

function tianjia() {
    localStorage.setItem('name', JSON.stringify($('.xingxi input:eq(0)').val()))
    localStorage.setItem('nick', JSON.stringify($('.xingxi input:eq(1)').val()))
    localStorage.setItem('img', JSON.stringify($('.xingxi input:eq(2)').val()))
    localStorage.setItem('iphone', JSON.stringify($('.xingxi input:eq(3)').val()))
    localStorage.setItem('birthdata', JSON.stringify($('.xingxi input:eq(4)').val()))
    localStorage.setItem('emails', JSON.stringify($('.xingxi input:eq(5)').val()))
    localStorage.setItem('indata', JSON.stringify($('.xingxi input:eq(6)').val()))
    $.ajax({
        type: 'post',
        url: 'http://47.94.4.201/index.php/index/index/mycenter',
        data: {
            name: $('.xingxi input:eq(0)').val(),
            userid: 1,
            img: $('.xingxi input:eq(2)').val(),
            iphone: $('.xingxi input:eq(3)').val(),
            nick: $('.xingxi input:eq(1)').val(),
            birthdata: $('.xingxi input:eq(4)').val(),
            emails: $('.xingxi input:eq(5)').val(),
            indata: $('.xingxi input:eq(6)').val(),
        },
        success: (a) => {
            if (a.msg == '添加成功') {
                document.querySelector('.xingxi').style.display = 'none'
                document.querySelector('.zhu').style.display = 'block'
                document.querySelector('.layui-nav-img').src = $('.xingxi input:eq(2)').val()
                document.querySelector('.user_img').src = $('.xingxi input:eq(2)').val()
                document.querySelector('.big_name').innerHTML = $('.xingxi input:eq(0)').val()
            } else {
                alert('添加失败')
            }
        },
        error: e => {
            console.log(e);
        }
    })
}


// ----------------------------------查看个人中心详情----------------------------
function center() {
    $('.xingxi').css('display', 'none')
    $('.zhu').css('display', 'none')
    $('.geren').css('display', 'block')
    $('.jia').css('display', 'none')
    $('.bji').css('display', 'none')
    $('.tubiao').css('display', 'none')
    var name = JSON.parse(localStorage.getItem('name'))
    var iphone = JSON.parse(localStorage.getItem('iphone'))
    var nick = JSON.parse(localStorage.getItem('nick'))
    var birthdata = JSON.parse(localStorage.getItem('birthdata'))
    var emails = JSON.parse(localStorage.getItem('emails'))
    var indata = JSON.parse(localStorage.getItem('indata'))
    var img = JSON.parse(localStorage.getItem('img'))

    $.ajax({
        type: 'get',
        url: 'http://47.94.4.201/index.php/index/index/getmycenter',
        data: {
            userid: 1
        },
        dataType: 'json',
        success: a => {
            if (a.msg == '个人中心详情') {
                document.querySelector('.one').innerHTML = name
                document.querySelector('.two').value = nick
                document.querySelector('.three').value = birthdata
                document.querySelector('.ipon').value = iphone
                document.querySelector('.eml').value = emails
                document.querySelector('.in').value = indata
                document.querySelector('.img').src = img
            }
        },
        error: e => {
            console.log(e);
        }
    })
}


// ----------------------------------添加讲师-----------------------------------
function kuang() {
    document.querySelector('.jia').style.display = 'block'
    document.querySelector('.zhu').style.display = 'none'
}

function add() {
    var sex
    var inps = document.querySelectorAll('.gend')
    inps.forEach(item => {
        if (item.checked) {
            sex = item.value
        }
    })

    $.ajax({
        type: 'post',
        url: 'http://47.94.4.201/index.php/index/index/addteacher',
        data: {
            name: document.querySelectorAll('.jia input')[0].value,
            nick: document.querySelectorAll('.jia input')[1].value,
            birthdata: document.querySelectorAll('.jia input')[2].value,
            iphone: document.querySelectorAll('.jia input')[3].value,
            sex: sex
        },
        success: (a) => {
            if (a.msg == '添加成功') {
                document.querySelector('.jia').style.display = 'none'
                document.querySelector('.zhu').style.display = 'block'
                fetchData(1)
            } else {
                alert('格式不正确')
            }
        },
        error: e => {
            console.log(e);
        }
    })
}

// -------------------------------------查看详情------------------------------------
layui.use(function () {
    var layer = layui.layer;
    var util = layui.util;
    // 批量事件
    util.on('lay-on', {
        page: function () {
            // 页面层
            layer.open({
                type: 1,
                area: ['800px', '500px'], // 宽高
                content: '<table border="1px" style="border-spacing: 0px"><tbody><tr><td>姓名:</td><td>李清照123</td><td>职位:</td><td colspan="2">讲师</td><td rowspan="4"><img src="./李清照.png" style="width: 100px;height: 100px;"></td></tr><tr><td>花名:</td><td>易安居士</td><td>出生日期:</td><td colspan="2">1970-01-01</td></tr><tr><td>性别:</td><td>女</td><td>入职日期:</td><td colspan="2">2015-02-14</td></tr><tr><td>手机号码:</td><td colspan="2"></td><td>邮箱:</td><td>liqingzhao@itcast.cn</td></tr><tr><td>籍贯:</td><td colspan="5">山东省 济南市 章丘市</td></tr><tr><td colspan="6"><textarea style="width: 690px;height: 100px;"></textarea></td></tr></tbody></table>'
            });
        }
    });
});

function look(id) {
    $.ajax({
        type: 'post',
        url: 'http://47.94.4.201/index.php/index/index/getteacherbyid',
        data: {
            id: id
        },
        success: (a) => {
            if (a.data.sex == 0) {
                a.data.sex = '男'
            } else if (a.data.sex == 1) {
                a.data.sex = '女'
            } else {
                a.data.sex = '其他'
            }

            var b = $('.layui-layer-content table')
            b.html('')
            b.append(`
                <tbody class='clears'>
            <tr>
                <td>姓名:</td>
                <td>${a.data.name}</td>
                <td>职位:</td>
                <td colspan="2">讲师</td>
                <td rowspan="4"><img src="./李清照.png" style="width: 100px;height: 100px;"></td>
            </tr>
            <tr>
                <td>花名:</td>
                <td>${a.data.nick}</td>
                <td>出生日期:</td>
                <td colspan="2">${a.data.birthdata}</td>
            </tr>
            <tr>
                <td>性别:</td>
                <td>${a.data.sex}</td>
                <td>入职日期:</td>
                <td colspan="2">2015-02-14</td>
            </tr>
            <tr>
                <td>手机号码:</td>
                <td colspan="2">${a.data.iphone}</td>
                <td>邮箱:</td>
                <td>liqingzhao@itcast.cn</td>
            </tr>
            <tr>
                <td>籍贯:</td>
                <td colspan="5">山东省 济南市 章丘市</td>
            </tr>
            <tr>
                <td colspan="6"><textarea style="width: 690px;height: 100px;"></textarea></td>
            </tr>
        </tbody>`)
        },
        error: e => {
            console.log(e);
        }
    })
}


// -------------------------------搜索-----------------------------------
function sou() {
    $.ajax({
        type: 'get',
        url: 'http://47.94.4.201/index.php/index/teacher/getsearch',
        data: {
            page: 1,
            pagelimit: 10,
            name: $('.content').val()
        },
        dataType: 'json',
        success: a => {
            a.data.data.forEach(item => {
                if (item.sex == 0) {
                    item.sex = '男'
                } else if (item.sex == 1) {
                    item.sex = '女'
                } else {
                    item.sex = '其他'
                }
            })

            var tbody = $('tbody')
            tbody.html('')
            a.data.data.forEach(item => {
                tbody.append(`
                    <tr>
                        <td>${item.id}</td>
                        <td>${item.name}</td>
                        <td>${item.nick}</td>
                        <td>${item.birthdata}</td>
                        <td>${item.sex}</td>
                        <td>${item.iphone}</td>
                        <td><button type="button" class="layui-btn layui-btn-primary" lay-on="page" onclick="look(${item.id})" id='look'>查看</button> 
                        <button onclick="bji(${item.id})" id='look'>编辑</button> 
                        <button class="del" onclick="del(${item.id})">删除</button></td>
                    </tr>`)
            })
        },
        error: e => {
            console.log(e);
        }
    })
}

// --------------------------------删除-----------------------------
function del(id) {
    $.ajax({
        type: 'get',
        url: 'http://47.94.4.201/index.php/index/teacher/delteacher',
        data: {
            id: id
        },
        dataType: 'json',
        success: a => {
            fetchData(1)
        },
        error: e => {
            console.log(e);
        }
    })
}


// -----------------------------编辑----------------------------
var iid
function bji(id) {
    $('.bji').css('display', 'block')
    $('.zhu').css('display', 'none')
    iid = id
}

function gai() {
    var sex
    var inps = document.querySelectorAll('.xbie')
    inps.forEach(item => {
        if (item.checked) {
            sex = item.value
        }
    })

    $.ajax({
        type: 'post',
        url: 'http://47.94.4.201/index.php/index/index/upteacher',
        data: {
            id: iid,
            name: $('.bji input:eq(0)').val(),
            birthdata: $('.bji input:eq(1)').val(),
            sex: sex,
        },
        dataType: 'json',
        success: a => {
            fetchData(1)
            $('.bji').css('display', 'none')
            $('.zhu').css('display', 'block')
        },
        error: e => {
            console.log(e);
        }
    })
}

// 退出登录
function tui() {
    location.assign('../登录/登录.html')
    localStorage.clear()
}


// 用户名
var use = JSON.parse(localStorage.getItem('loog'))
document.querySelector('.layui-nav-img').src = JSON.parse(localStorage.getItem('img'))
document.querySelector('.user_img').src = JSON.parse(localStorage.getItem('img'))
document.querySelector('.big_name').innerHTML = JSON.parse(localStorage.getItem('name'))
var iig = 'https://img1.baidu.com/it/u=3029394063,3849121399&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1741366800&t=facbf90abffc6ddee538c6252f10e09e'
document.querySelectorAll('.big_name').forEach(item => {
    if (!localStorage.getItem('name')) {
        item.innerHTML = use
    }
})
document.querySelectorAll('.layui-nav-img').forEach(item => {
    if (!localStorage.getItem('img')) {
        item.src = iig
    }
})